package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.ServletUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.FamilyMemberElderPageDto;
import com.zzyl.nursing.dto.MyFamilyDto;
import com.zzyl.nursing.mapper.BedMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.FamilyMemberElderService;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.vo.BindingFamilyVo;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class FamilyMemberElderServiceImpl extends ServiceImpl<FamilyMemberElderMapper, FamilyMemberElder> implements FamilyMemberElderService {
    @Autowired
    private IFamilyMemberService familyMemberService;

    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IElderService elderService;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private DeviceMapper deviceMapper;
    /**
     * 查看家属列表分页查询
     */
    @Override
    public List<FamilyMemberElderPageDto> getPageList(Integer pageNum, Integer pageSize) {
        Page<FamilyMemberElder> page = new Page<>(pageNum, pageSize);
        Long userId = getCurrentUserId();
        Page<FamilyMemberElder> familyMemberElderPage = familyMemberElderMapper.selectPage(page, Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, userId));
        if (familyMemberElderPage.getRecords().isEmpty()) {
            return Collections.emptyList();
        }
        List<FamilyMemberElderPageDto> list = new ArrayList<>();
        familyMemberElderPage.getRecords().forEach(familyMemberElder -> {
            FamilyMemberElderPageDto familyMemberElderPageDto = new FamilyMemberElderPageDto();
            familyMemberElderPageDto.setMid(familyMemberElder.getId());
            familyMemberElderPageDto.setMremark(familyMemberElder.getRemark());
            familyMemberElderPageDto.setElderId(familyMemberElder.getElderId());
            Elder elder = elderService.selectElderById(familyMemberElder.getElderId());
            familyMemberElderPageDto.setName(elder.getName());
            familyMemberElderPageDto.setImage(elder.getImage());
            familyMemberElderPageDto.setBedNumber(elder.getBedNumber());
            Bed bed = bedMapper.selectOne(Wrappers.<Bed>lambdaQuery().eq(Bed::getBedNumber, elder.getBedNumber()));
            Room room = roomMapper.selectOne(Wrappers.<Room>lambdaQuery().eq(Room::getId, bed.getRoomId()));
            familyMemberElderPageDto.setTypeName(room.getTypeName());
            Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getBindingLocation, elder.getId()));
            if (ObjectUtil.isNotEmpty(device)){
                familyMemberElderPageDto.setIotId(device.getIotId());
                familyMemberElderPageDto.setDeviceName(device.getDeviceName());
                familyMemberElderPageDto.setProductKey(device.getProductKey());
            }
            list.add(familyMemberElderPageDto);
        });
        return list;
    }
    /**
     * 查询家属分页
     */
    @Override
    public List<MyFamilyDto> myFamilyQueryPage(Integer pageNum, Integer pageSize) {
        Page<FamilyMemberElder> page = new Page<>(pageNum, pageSize);
        Long userId = getCurrentUserId();
        Page<FamilyMemberElder> familyMemberElderPage = familyMemberElderMapper.selectPage(page, Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, userId));
        if (familyMemberElderPage.getRecords().isEmpty()) {
            return Collections.emptyList();
        }
        ArrayList<MyFamilyDto> myFamilyDtos = new ArrayList<>();
        familyMemberElderPage.getRecords().forEach(
                familyMemberElder -> {
                    MyFamilyDto myFamilyDto = new MyFamilyDto();
                    myFamilyDto.setFamilyMemberId(userId);
                    myFamilyDto.setId(familyMemberElder.getId());
                    myFamilyDto.setElderId(familyMemberElder.getElderId());
                    Elder elder = elderService.selectElderById(familyMemberElder.getElderId());
                    myFamilyDto.setElderName(elder.getName());
                    myFamilyDtos.add(myFamilyDto);
                }
        );
        return myFamilyDtos;
    }



    /**
     * 绑定老人
     */
    @Override
    public void bindingFamily(BindingFamilyVo vo) {
        Elder elder = elderService.getOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, vo.getIdCard()));
        Long count = familyMemberElderMapper.selectCount(Wrappers.<FamilyMemberElder>lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(elder.getId()),FamilyMemberElder::getElderId, elder.getId()));
        if (elder == null) {
            throw new BaseException("查无此家属！");
        }
        if (count > 0) {
            throw new BaseException("老人已被绑定！");
        }
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        //获取当前登录用户id
        Long currentUserId = getCurrentUserId();
        FamilyMember familyMember = familyMemberService.getOne(Wrappers.<FamilyMember>lambdaQuery()
                .eq(FamilyMember::getId, currentUserId));
        familyMemberElder.setCreateBy(familyMember.getName());
        familyMemberElder.setFamilyMemberId(currentUserId);
        familyMemberElder.setRemark(vo.getRemark());
        familyMemberElder.setElderId(elder.getId());
        familyMemberElder.setCreateTime(LocalDateTime.now());
        familyMemberElder.setUpdateTime(LocalDateTime.now());
        familyMemberElder.setUpdateBy(currentUserId.toString());
        familyMemberElderMapper.insert(familyMemberElder);
    }

    /**
     * 获取当前用户信息
     */

    public Long getCurrentUserId() {
        // 从当前请求中获取token
        HttpServletRequest request = ServletUtils.getRequest();
        String token = tokenService.getToken(request);

        if (StringUtils.isNotEmpty(token)) {
            try {
                // 解析token获取claims
                Claims claims = tokenService.parseToken(token);
                if (claims != null && claims.containsKey("userId")) {
                    return Long.valueOf(claims.get("userId").toString());
                }
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
}
